package com.guosen.zebra.gateway.route.parser;

import com.guosen.zebra.gateway.route.model.RouteInfo;
import com.guosen.zebra.gateway.route.model.RouteConfig;
import com.guosen.zebra.gateway.route.model.SubUrlMethodMapping;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 具体 URL 路由信息解析器
 */
public final class ConcreteUrlRouteInfoParser {

    private ConcreteUrlRouteInfoParser(){}

    /**
     * 解析具体 URL 路由信息
     * @param routeConfig   路由配置
     * @return  具体 URL 路由信息
     */
    public static Map<String, RouteInfo> parse(RouteConfig routeConfig) {
        Map<String, RouteInfo> concreteUrlRouteInfoMap = new HashMap<>();

        List<SubUrlMethodMapping> subUrlMethodMappings =
                SubUrlMethodMappingParser.parse(routeConfig.getMethodMappings());
        if (CollectionUtils.isEmpty(subUrlMethodMappings)) {
            return concreteUrlRouteInfoMap;
        }

        for (SubUrlMethodMapping subUrlMethodMapping : subUrlMethodMappings) {
            String wholeUrl = getWholeUrl(routeConfig, subUrlMethodMapping);
            RouteInfo newRouteInfo = getRouteInfo(routeConfig, subUrlMethodMapping);
            concreteUrlRouteInfoMap.put(wholeUrl, newRouteInfo);
        }

        return concreteUrlRouteInfoMap;
    }

    private static String getWholeUrl(RouteConfig routeConfig, SubUrlMethodMapping subUrlMethodMapping) {
        String subUrl = subUrlMethodMapping.getSubUrl();
        return routeConfig.getUrlPrefix() + subUrl;
    }

    private static RouteInfo getRouteInfo(RouteConfig routeConfig, SubUrlMethodMapping subUrlMethodMapping) {
        String methodName = subUrlMethodMapping.getMethod();

        RouteInfo newRouteInfo = toRouteInfo(routeConfig);
        newRouteInfo.setMethod(methodName);
        return newRouteInfo;
    }

    private static RouteInfo toRouteInfo(RouteConfig routeConfig) {
        return RouteInfo.newBuilder()
                .serviceName(routeConfig.getServiceName())
                .version(routeConfig.getVersion())
                .group(routeConfig.getGroup())
                .urlPrefix(routeConfig.getUrlPrefix())
                .build();
    }
}
